<template>
  <div class="auth-bg">
    <loginarea></loginarea>
    <div class="auth-form login-form">
      <div class="inner">
        <div class="form-legend">{{ '云智易物联云平台企业管理台' }}</div>
        <div class="form">
          <form novalidate @submit.prevent="onSubmit">
            <div class="form-row">
              <div class="input-text-wrap">
                <input 
                  ref="account"
                  placeholder="邮箱/手机号"
                  type="text"
                  v-model="model.account"
                  name="model.account"
                  class="input-text"
                  :class="{'error': validate.account === 2}"
                  @blur.prevent="onblur('account', $event)"/>
              </div>
              <div class="form-tips form-tips-error">
                <span v-if="validate.account === 2">请输入帐号</span>
              </div>
            </div>
            <div class="form-row">
              <div class="input-text-wrap">
                <input
                  placeholder="密码"
                  type="password"
                  v-model="model.password"
                  name="model.password"
                  class="input-text"
                  :class="{'error': validate.password === 2}"
                  @blur.prevent="onblur('password', $event)"/>
              </div>
              <div class="form-tips form-tips-error">
                <span v-if="validate.password === 2">请输入密码</span>
              </div>
            </div>
            <div class="form-row row-check">
              <label class="checkbox">
                <input type="checkbox" v-model="rememberPwd"/>记住密码
              </label>
            </div>
            <div class="form-actions">
              <button 
                @keyup.enter="onSubmit"
                :disabled="logining"
                :class="{'disabled':logining}"
                v-text="logining ? '登录中...' : '登录'"
                class="btn btn-primary btn-xxlg btn-pill focus-input"
                >
                登录
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import Loginarea from '../../components/view/layout/loginarea'
  import api from 'api'

  const VALIDATE_CODE = {
    NOVALIDATE: 0,
    SUCCESS: 1,
    FAIL: 2
  }

  export default {
    name: 'Login',

    components: {
      Loginarea
    },

    data () {
      return {
        logining: false,
        model: {
          account: '',
          password: ''
        },
        validate: {
          account: VALIDATE_CODE.NOVALIDATE,
          password: VALIDATE_CODE.NOVALIDATE,
          isValid () {
            if (this.account === VALIDATE_CODE.SUCCESS && this.password === VALIDATE_CODE.SUCCESS) {
              return true
            }
            return false
          }
        },
        isLoginSuccess: false,
        rememberPwd: Boolean(this.getCookie('rememberPwd')) || false
      }
    },

    route: {
      canActivate (transition) {
        transition.next()
      }
    },

    mounted () {
      this.$refs.account.focus()
      if (this.rememberPwd) {
        this.model.account = this.getCookie('account')
        this.model.password = this.getCookie('password')
      }
    },

    methods: {
      // 设置 Cookies
      setCookie (name, value) {
        var Days = 30
        var exp = new Date()
        exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000)
        document.cookie = name + '=' + escape(value) + ';expires=' + exp.toGMTString()
      },

      // 读取 Cookies
      getCookie (name) {
        var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
        var arr = document.cookie.match(reg) || {}
        if (arr.length) {
          return unescape(arr[2])
        } else {
          return null
        }
      },

      // 删除 Cookies
      delCookie (name) {
        var exp = new Date()
        exp.setTime(exp.getTime() - 1)
        var cval = this.getCookie(name)
        if (cval != null) {
          document.cookie = name + '=' + cval + ';expires=' + exp.toGMTString()
        }
      },
      onSubmit () {
        this.verify()
        console.log(this.validate.isValid())
        if (!this.validate.isValid()) {
          return
        }

        if (this.logining) {
          return
        }

        this.logining = true

        api.corp.auth(this.model).then((res) => {
          window.localStorage.setItem('memberId', res.data.member_id)
          window.localStorage.setItem('corpId', res.data.corp_id)
          window.localStorage.setItem('accessToken', res.data.access_token)
          window.localStorage.setItem('refreshToken', res.data.refresh_token)
          if (this.rememberPwd) {
            this.setCookie('rememberPwd', true)
            this.setCookie('account', this.model.account)
            this.setCookie('password', this.model.password)
          } else {
            this.delCookie('rememberPwd')
            this.delCookie('account')
            this.delCookie('password')
          }

          this.$router.replace({path: '/dashboard/monitor'})
        }).catch((res) => {
          this.logining = false
        })
      },
      verify () {
        for (let i in this.model) {
          if (this.model[i]) {
            this.validate[i] = VALIDATE_CODE.SUCCESS
          } else {
            this.validate[i] = VALIDATE_CODE.FAIL
          }
        }
      },
      onblur (name, event) {
        if (!event.target.value) {
          this.validate[name] = VALIDATE_CODE.FAIL
        } else {
          this.validate[name] = VALIDATE_CODE.SUCCESS
        }
      }
    }
  }
</script>

<style lang="stylus" scoped>
  @import '../../assets/stylus/base'
  @import './index.styl'
</style>
